package com.lwc.backendsinglestructure.strategy.loginStrategy;

import com.lwc.backendsinglestructure.domain.dto.user.LoginForm;
import com.lwc.backendsinglestructure.domain.entity.User;
import com.lwc.backendsinglestructure.exception.BusinessException;
import com.lwc.backendsinglestructure.exception.ErrorCode;
import com.lwc.backendsinglestructure.mapper.UserMapper;
import com.lwc.backendsinglestructure.strategy.LoginHandler;
import com.mybatisflex.core.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 手机号登录
 */
@Component("phone_Login")
public class PhoneLoginHandler implements LoginHandler {

    @Autowired
    private UserMapper userMapper;

    @Override
    public User login(LoginForm loginRequest) {
        // todo 1.根据手机号去查询用户 / 包括用户的状态 用户是否存在
        String phone = loginRequest.getPhone();
        if(phone == null){
            throw new BusinessException(ErrorCode.PHONE_NOT_FOUND_ERROR);
        }
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("phone", phone);
        User user = userMapper.selectOneByQuery(wrapper);
        //  2.如果用户不存在，则自动帮助用户注册一个新用户，并且返回登录信息
        if(user == null){
            throw new BusinessException(ErrorCode.USER_NOT_FOUND_ERROR);
        }
        // todo 3.如果用户存在，则比对发送的短信验证码 一致允许登录

        return user;
    }
}
